<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-row style="padding: 10px 0px;">
            <el-col :span="2">
              <span style="font-size:.9rem">{{ parseTime(new Date(new Date().toDateString())).replace(' 00:00:00', '') }}</span>
            </el-col>
            <el-col :span="22">
              <el-button :type="query.button.css.status.all" size="small" @click.native="queryByState('all')" >全部</el-button>
              <el-button  size="mini" :type="query.button.css.status.unPay" @click.native="queryByState('unPay')">待付款 &nbsp;<el-tag type="success"  size="mini">{{query.button.tag.unPay}}</el-tag></el-button>
              <el-button  size="mini" :type="query.button.css.status.unSend" @click.native="queryByState('unSend')">待发货&nbsp;<el-tag type="danger"  size="mini">{{query.button.tag.unSend}}</el-tag></el-button>
              <el-button  size="mini" :type="query.button.css.status.sended" @click.native="queryByState('sended')">已发货&nbsp;<el-tag type="info"  size="mini">{{query.button.tag.sended}}</el-tag></el-button>
              <el-button  size="mini" :type="query.button.css.status.finished" @click.native="queryByState('finished')">已完成&nbsp;<el-tag type="info"  size="mini">{{query.button.tag.finished}}</el-tag></el-button>
              <el-button  size="mini" :type="query.button.css.status.cancel" @click.native="queryByState('cancel')">已取消&nbsp;<el-tag type="info"  size="mini">{{query.button.tag.cancel}}</el-tag></el-button>
              <el-button  size="mini" :type="query.button.css.status.refundIng" @click.native="queryByState('refundIng')">退款中&nbsp;<el-tag type="danger"  size="mini">{{query.button.tag.refundIng}}</el-tag></el-button>
              <el-button  size="mini" :type="query.button.css.status.refund" @click.native="queryByState('refund')">已退款&nbsp;<el-tag type="info"  size="mini">{{query.button.tag.refund}}</el-tag></el-button>
            </el-col>
          </el-row>
          <el-row style="padding: 10px 0px;">
            <el-col :span="2">
              <span style="font-size:.9rem;">下单日期：</span>
            </el-col>
            <el-col :span="22">
              <el-button size="small" :type="query.button.css.date.all"  @click.native="queryByDate('all')">全部</el-button>
              <el-button  size="small" :type="query.button.css.date.today"  @click.native="queryByDate('today')">今天</el-button>
              <el-button  size="small" :type="query.button.css.date.yesterday"  @click.native="queryByDate('yesterday')">昨天</el-button>
              <el-button  size="small" :type="query.button.css.date.seven"  @click.native="queryByDate('seven')">最近7天</el-button>
              <el-button  size="small" :type="query.button.css.date.thirty"  @click.native="queryByDate('thirty')">最近30天</el-button>
              <el-button  size="small" :type="query.button.css.date.month"  @click.native="queryByDate('month')">本月</el-button>
              <el-button  size="small" :type="query.button.css.date.year"  @click.native="queryByDate('year')">本年</el-button>
              <el-button  size="small" :type="query.button.css.date.customer"  @click.native="queryByDate('customer')">自定义</el-button>
              <el-date-picker
                v-if="query.button.showCustomer"
                v-model="dateRangeCreateTime"
                size="mini"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="截至日期">
              </el-date-picker>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="5" style="padding: 10px 0px;">
          <el-form-item prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入收件人电话"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5" style="padding: 10px 0px;">
          <el-form-item prop="orderSn">
            <el-input
              v-model="queryParams.orderSn"
              placeholder="请输入订单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" style="padding: 10px 0px;">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:shopOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:shopOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:shopOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['shop:shopOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" align="center" prop="id" v-if="false"/>
      <el-table-column label="用户" align="center" prop="mobile">
        <template slot-scope="scope">
          <router-link :to="{ name: 'ShopUserDetail', query: { id: scope.row.idUser } }">
            {{scope.row.mobile}}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="orderSn">
        <template slot-scope="scope">
          <router-link :to="{ name: 'ShopOrderDetail', query: { orderSn: scope.row.orderSn } }">
            {{scope.row.orderSn}}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="订单状态" align="center" prop="statusName" />
      <el-table-column label="支付状态" align="center" prop="payStatusName" />
      <el-table-column label="实付类型" align="center" prop="payTypeName" />
      <el-table-column label="总金额" align="center" prop="totalPrice">
        <template slot-scope="scope">
          {{formatPrice(scope.row.totalPrice)}}
        </template>
      </el-table-column>
      <el-table-column label="订单备注" align="center" prop="message" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:shopOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:shopOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="idUser">
          <el-input v-model="form.idUser" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="优惠券抵扣金额" prop="couponPrice">
          <el-input v-model="form.couponPrice" placeholder="请输入优惠券抵扣金额" />
        </el-form-item>
        <el-form-item label="交易金额" prop="tradeAmount">
          <el-input v-model="form.tradeAmount" placeholder="请输入交易金额" />
        </el-form-item>
        <el-form-item label="实付金额" prop="realPrice">
          <el-input v-model="form.realPrice" placeholder="请输入实付金额" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="支付流水号" prop="payId">
          <el-input v-model="form.payId" placeholder="请输入支付流水号" />
        </el-form-item>
        <el-form-item label="支付成功时间" prop="payTime">
          <el-input v-model="form.payTime" placeholder="请输入支付成功时间" />
        </el-form-item>
        <el-form-item label="收件人" prop="consignee">
          <el-input v-model="form.consignee" placeholder="请输入收件人" />
        </el-form-item>
        <el-form-item label="收件人电话" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入收件人电话" />
        </el-form-item>
        <el-form-item label="收件地址" prop="consigneeAddress">
          <el-input v-model="form.consigneeAddress" placeholder="请输入收件地址" />
        </el-form-item>
        <el-form-item label="收货信息" prop="idAddress">
          <el-input v-model="form.idAddress" placeholder="请输入收货信息" />
        </el-form-item>
        <el-form-item label="快递公司" prop="idExpress">
          <el-input v-model="form.idExpress" placeholder="请输入快递公司" />
        </el-form-item>
        <el-form-item label="快递单号" prop="shippingSn">
          <el-input v-model="form.shippingSn" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="配送费用" prop="shippingAmount">
          <el-input v-model="form.shippingAmount" placeholder="请输入配送费用" />
        </el-form-item>
        <el-form-item label="出库时间" prop="shippingTime">
          <el-date-picker clearable
            v-model="form.shippingTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择出库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="确认收货时间" prop="confirmReceivingTime">
          <el-date-picker clearable
            v-model="form.confirmReceivingTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择确认收货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单备注" prop="message">
          <el-input v-model="form.message" placeholder="请输入订单备注" />
        </el-form-item>
        <el-form-item label="管理员备注" prop="adminMessage">
          <el-input v-model="form.adminMessage" placeholder="请输入管理员备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShopOrder, getShopOrder, delShopOrder, addShopOrder, updateShopOrder } from "@/api/shop/shopOrder";

export default {
  name: "ShopOrder",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      shopOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        idUser: undefined,
        orderSn: undefined,
        status: undefined,
        couponPrice: undefined,
        tradeAmount: undefined,
        realPrice: undefined,
        totalPrice: undefined,
        payStatus: undefined,
        payId: undefined,
        payType: undefined,
        payTime: undefined,
        consignee: undefined,
        mobile: undefined,
        consigneeAddress: undefined,
        idAddress: undefined,
        idExpress: undefined,
        shippingSn: undefined,
        shippingAmount: undefined,
        shippingTime: undefined,
        confirmReceivingTime: undefined,
        message: undefined,
        adminMessage: undefined,
      },
      query:{
        button:{
          lastStatus:'all',
          lastDate:'all',
          showCustomer:false,
          css:{
            status: {
              all: 'primary',
              unPay: 'default',
              unSend: 'default',
              sended: 'default',
              finished: 'default',
              cancel: 'default',
              refundIng: 'default',
              refund: 'default'
            },
            date:{
              all: 'primary',
              today: 'default',
              yesterday: 'default',
              seven: 'default',
              thirty:'default',
              month: 'default',
              year: 'default',
              customer: 'default'
            }
          },
          tag:{
            unPay:0,
            unSend:0,
            sended:0,
            finished:0,
            cancel:0,
            refundIng:0,
            refund:0
          }
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        idUser: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        orderSn: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        couponPrice: [
          { required: true, message: "优惠券抵扣金额不能为空", trigger: "blur" }
        ],
        tradeAmount: [
          { required: true, message: "交易金额不能为空", trigger: "blur" }
        ],
        realPrice: [
          { required: true, message: "实付金额不能为空", trigger: "blur" }
        ],
        totalPrice: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
        payStatus: [
          { required: true, message: "支付状态1:未付款;2:已付款,3:支付中不能为空", trigger: "change" }
        ],
        payId: [
          { required: true, message: "支付流水号不能为空", trigger: "blur" }
        ],
        payType: [
          { required: true, message: "实付类型:alipay,wechat不能为空", trigger: "change" }
        ],
        payTime: [
          { required: true, message: "支付成功时间不能为空", trigger: "blur" }
        ],
        consignee: [
          { required: true, message: "收件人不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "收件人电话不能为空", trigger: "blur" }
        ],
        consigneeAddress: [
          { required: true, message: "收件地址不能为空", trigger: "blur" }
        ],
        idAddress: [
          { required: true, message: "收货信息不能为空", trigger: "blur" }
        ],
        idExpress: [
          { required: true, message: "快递公司不能为空", trigger: "blur" }
        ],
        shippingSn: [
          { required: true, message: "快递单号不能为空", trigger: "blur" }
        ],
        shippingAmount: [
          { required: true, message: "配送费用不能为空", trigger: "blur" }
        ],
        shippingTime: [
          { required: true, message: "出库时间不能为空", trigger: "blur" }
        ],
        confirmReceivingTime: [
          { required: true, message: "确认收货时间不能为空", trigger: "blur" }
        ],
        message: [
          { required: true, message: "订单备注不能为空", trigger: "blur" }
        ],
        adminMessage: [
          { required: true, message: "管理员备注不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;

      listShopOrder(this.addDateRange(this.queryParams, this.dateRangeCreateTime, "CreateTime")).then(response => {
        this.shopOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        idUser: undefined,
        orderSn: undefined,
        status: undefined,
        couponPrice: undefined,
        tradeAmount: undefined,
        realPrice: undefined,
        totalPrice: undefined,
        payStatus: undefined,
        payId: undefined,
        payType: undefined,
        payTime: undefined,
        consignee: undefined,
        mobile: undefined,
        consigneeAddress: undefined,
        idAddress: undefined,
        idExpress: undefined,
        shippingSn: undefined,
        shippingAmount: undefined,
        shippingTime: undefined,
        confirmReceivingTime: undefined,
        message: undefined,
        adminMessage: undefined,
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    queryByState(status){
      const lastStatus = this.query.button.lastStatus
      this.query.button.css.status[lastStatus]='default'
      this.query.button.css.status[status] = 'primary'
      this.query.button.lastStatus = status
      if(status !== 'all') {
        this.queryParams.status = status
      }else{
        this.queryParams.status = ''
      }
      this.getList();
    },
    queryByDate(date){
      const lastDate = this.query.button.lastDate
      this.query.button.css.date[lastDate]='default'
      this.query.button.css.date[date] = 'primary'
      this.query.button.lastDate = date
      this.dateRangeCreateTime = [];
      if(date !== 'all' && date !=='customer') {
        this.setDateRange(date);
        console.info(this.dateRangeCreateTime);
      }
      if(date === 'customer'){
        this.query.button.showCustomer=true
        return
      }else{
        this.query.button.showCustomer=false
      }
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getShopOrder(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改订单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateShopOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addShopOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单管理编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delShopOrder(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shop/shopOrder/export', {
        ...this.queryParams
      }, `shopOrder_${new Date().getTime()}.xlsx`)
    },
    setDateRange(date){
      var nowDate = new Date(new Date().toDateString())
      var nowFormat = this.parseTime(nowDate).replace(' 00:00:00', '');
      switch (date) {
        case "today":
          this.dateRangeCreateTime.push(nowFormat + " 00:00:00", nowFormat + " 23:59:59");
          break;
        case "yesterday":
          var yesterday = nowDate.setDate(nowDate.getDate() - 1);
          var yesterdayFmt = this.parseTime(yesterday).replace(' 00:00:00', '');;
          this.dateRangeCreateTime.push(yesterdayFmt + " 00:00:00", yesterdayFmt + " 23:59:59");
          break;
        case "seven":
          var last7Date = nowDate.setDate(nowDate.getDate() - 7);
          var last7DateFmt = this.parseTime(last7Date).replace(' 00:00:00', '');;
          this.dateRangeCreateTime.push(last7DateFmt + " 00:00:00", nowFormat + " 23:59:59");
          break;
        case "thirty":
          var last30Date = nowDate.setDate(nowDate.getDate() - 30);
          var last30DateFmt = this.parseTime(last30Date).replace(' 00:00:00', '');;
          this.dateRangeCreateTime.push(last30DateFmt + " 00:00:00", nowFormat + " 23:59:59");
          break;
        case "month":
          var currentMonth = nowDate.setDate(1);
          var currentMonthFmt = this.parseTime(currentMonth).replace(' 00:00:00', '');;
          this.dateRangeCreateTime.push(currentMonthFmt + " 00:00:00", nowFormat + " 23:59:59");
          break;
        case "year":
          nowDate.setMonth(0);
          var currentYear = nowDate.setDate(1);
          var currentYearFmt = this.parseTime(currentYear).replace(' 00:00:00', '');;
          this.dateRangeCreateTime.push(currentYearFmt + " 00:00:00", nowFormat + " 23:59:59");
          break;
        default:
          break;
      }
    },
    formatPrice(price) {
      return (price / 100).toFixed(2);
    },
  }
};
</script>

<style scoped>
  a{
    color: lightblue;
    text-decoration: underline;
  }
</style>
